<!--
  Copyright 2016 The LUCI Authors. All rights reserved.
  Use of this source code is governed under the Apache License, Version 2.0
  that can be found in the LICENSE file.
-->

<link rel="import" href="../../inc/bower_components/polymer/polymer.html">

<!-- Inline our main TypeScript -->
<script src="../../inc/apps/logdog-view/main.js"></script>

<link rel="import" href="../../inc/bower_components/paper-styles/default-theme.html">
<link rel="import" href="../../inc/bower_components/paper-styles/typography.html">

<link rel="import" href="../../inc/logdog-app-base/logdog-app-base.html">
<link rel="import" href="../../inc/logdog-stream-view/logdog-stream-view.html">
<link rel="import" href="../../inc/auth/auth-signin.html">

<link rel="stylesheet" href="../../styles/main.css">

<!--
An element for the LogDog lightweight view app of a single set of streams.

The streams are specified by full path using the "s=" query parameter.
-->
<dom-module id="logdog-view">

<template>
  <style>
    :host {
      @apply(--paper-font-common-base);
    }

    #banner {
      background-color: #FAFAFA;
      overflow: hidden;
      border-color: lightcoral;
      border-width: 0px 0px 2px 0px;
      border-style: solid;
    }

    .banner-content {
      width: auto;
      display: inline-block;
      padding-left: 5px;
      padding-right: 5px;
      overflow: hidden;
    }

    .banner-content h1 {
      font-size: 18px;
    }

    #auth-bubble {
      float: right;
      display: inline-block;
      border: none;
    }
  </style>

  <div>
    <div id="banner">
      <span class="banner-content">
        <h1><a href="/">LogDog</a>
          <template is="dom-if" if="{{_hasStreams}}">
            <template is="dom-if" if="{{streamLinkUrl}}">
              : <a href="{{streamLinkUrl}}">[[streams]]</a>
            </template>
            <template is="dom-if" if="{{!streamLinkUrl}}">
              : [[streams]]
            </template>
          </template>
          <template is="dom-if" if="{{!_hasStreams}}">
            (No Streams Provided)
          </template>
          (Dogfood the plain-text viewer <a href="/logs/[[streams]]">here</a>)
        </h1>
      </span>
      <template is="dom-if" if="{{clientId}}">
        <span id="auth-bubble">
          <auth-signin
              client-id="[[clientId]]"></auth-signin>
        </span>
      </template>
    </div>

    <logdog-stream-view
      id="streamView"
      host="[[host]]"
      mobile="[[mobile]]"
      metadata="[[metadata]]"
      streams="[[streams]]"
      stream-link-url="{{streamLinkUrl}}"></logdog-stream-view>
  </div>
</template>

</dom-module>

<script>
  Polymer({
    is: "logdog-view",
    properties: {
      host: {
        type: String,
        notify: true,
        value: null,
      },

      clientId: {
        type: String,
        value: null,
      },

      streams: {
        type: Array,
        value: [],
        readOnly: true,
      },

      streamLinkUrl: {
        type: String,
        value: null,
        notify: true,
      },

      metadata: {
        type: String,
        value: false,
        readOnly: true,
      },

      mobile: {
        type: Boolean,
        value: false,
      },

      _hasStreams: {
        computed: '_arrayHasElements(streams)',
      },
    },

    observers: [
      '_updatePageTitle(streams)',
    ],

    ready: function() {
      // Test if we're mobile.
      this.mobile = false;
      if ( window.matchMedia ) {
        this.mobile = window.matchMedia(
            "only screen and (max-width: 760px)").maches;
      }

      // Parse the stream names from the "s" query parameter.
      var queryString = window.location.search.replace(/^\?/, "");
      var streams = logdog.getQueryValues(queryString, "s").
          map(logdog.correctStreamPath);
      this._setStreams(streams);

      // Parse the metadata option.
      this._setMetadata(!!logdog.getQueryValue(queryString, "m", false));

      // Parse the host option.
      var host = logdog.getQueryValue(queryString, "h", undefined);
      if (host) {
        this.host = host;
      }
    },

    _onSignin: function(e) {
      this._setAccessToken(e.detail.access_token);
    },
    _onSignout: function(e) {
      this._setAccessToken(null);
    },

    _arrayHasElements: function(v) {
      return (v && v.length);
    },

    _updatePageTitle: function(streams) {
      var paths = (streams || []).map(s => LogDog.StreamPath.splitProject(s));

      var commonProject = this._getCommonStreamField(paths, p => p.project);
      var commonPrefix = this._getCommonStreamField(paths, p => p.prefix);

      var title = 'LogDog';
      if (commonProject) {
        title += '(' + commonProject + '): ';

        if (commonPrefix) {
          title += commonPrefix + '/+/ ';
        }
      } else {
        title += ': ';
      }

      if (paths.length) {
        var vals = paths.map(p => {
          if (commonProject) {
            if (commonPrefix) {
              return p.name;
            }
            return p.path;
          }
          return p.fullName();
        });

        if (commonProject && commonPrefix) {
          title += vals.join('&');
        } else {
          title += vals.join(' ');
        }
      }

      document.title = title;
    },

    _getCommonStreamField: function(paths, fn) {
      var commonValue;
      paths.forEach((path, idx) => {
        var v = fn(path);
        if (idx === 0) {
          commonValue = v;
        } else if (commonValue !== v) {
          commonValue = undefined;
          return false;
        }
        return true;
      });
      return commonValue;
    },
  });

  (function(i,s,o,g,r,a,m){i['CrDXObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://storage.googleapis.com/crdx-feedback.appspot.com/feedback.js','crdx');

  crdx('setFeedbackButtonLink', 'https://bugs.chromium.org/p/chromium/issues/entry?components=Infra>Platform>LogDog&labels=Infra-DX');
</script>
